import cv2
import matplotlib.pyplot as plt
import numpy as np


img = cv2.imread('../images/qp.jpg')
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
print("---灰度图---")
print(img)
img = cv2.medianBlur(img,5)#中值滤波
print("---中值滤波---")
print(img)
ret,th1 =cv2.threshold(img,127,255,cv2.THRESH_BINARY)
print("---阈值---")
print(th1)
#cv2.ADAPTIVE_THRESH_MEAN_C阈值取自相邻区的平均值，11：领域大小，2：是一个常数，阈值等于平均值或平均值减去这个常数
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
#ADAPTIVE_THRESH_GAUSSIAN_C：阈值取自邻区域的加权和，权重为一个高斯窗口
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
titles = ['Original image','Global Thresholding(v=127)','Adaptive Mean Thresholding','Adaptive Gaussian Thresholding']
images = [img,th1,th2,th3]
for i in range(4):
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

